package blockChain;

import java.util.Date;

/**
 * @author WuYongheng
 * @date 2022/10/22
 * @description
 */
public class Block {
    public String hash;
    public String previousHash;
    private String data;
    private long timeStamp;
    private int nonce;

    /**
     * 区块构造函数
     *
     * @param previousHash
     * @param data
     */
    public Block(String data, String previousHash) {
        this.previousHash = previousHash;
        this.data = data;
        this.timeStamp = new Date().getTime();
        this.hash = calculateHash();
    }

    /**
     * 计算区块的hash值，使用SHA256加密算法
     * nonce每加一次，都会调用一次applySha256()方法
     *
     * @return calculateHash
     */
    private String calculateHash() {
        String calculateHash = StringUtil.applySha256(
                previousHash
                        + Long.toString(timeStamp)
                        + data
                        + Integer.toString(nonce)
        );
        return calculateHash;
    }

    /**
     * 通过随机数nonce的递增，不断地尝试，得到符合要求的哈希值，使用SHA256加密
     * 人为制造哈希碰撞的可能性很低，可以认为随机数是唯一的
     *
     * @param difficulty 困难度，表示哈希值的开头有多少个零
     */
    public void mineBlock(int difficulty) {
        String target = StringUtil.getDifficultyString(difficulty);
        while (!hash.substring(0, difficulty).equals(target)) {
            nonce++;
            hash = calculateHash();
        }
        System.out.println("Block Mined!!! : " + hash);
    }

}
